import Vue from 'vue';
import Vuex from 'vuex';
const state = {
	user: {
		userId: null,
		account: '', //账号
		password: '',
		type: '', //类别
		nickname: '', //昵称
		image: '', //头像
		birthday: '',
	},
	activity_attend: [], //当前角色参与的活动列表
	user_shopping_cart: [], //当前用户的购物车
	addressList: [], //当前用户的地址
	goods_list: [], //当前商家所拥有的商品
}
const getters = {
	// 确定是否登陆
	getSure() {
		return state.user.account && state.user.password
	},
	// 获取购物车长度
	get_user_shopping_cart_length() {
		return state.user_shopping_cart.length
	},
	get_address_default() {
		return state.addressList.find((item, index) => {
			return item.isDefault == 1
		})
	}
}

const mutations = {
	//获取地址
	get_addressList(state, userId) {
		uni.request({
			url: 'http://localhost:3000/users/address',
			method: 'get',
			data: {
				id: userId
			},
			success: (res) => {
				state.addressList = res.data
				// console.log("地址res:", res)

				if (!state.addressList.some((item) => {
						return item.isDefault
					})) {
					state.addressList[0].isDefault = 1
					uni.request({
						url: 'http://localhost:3000/users/address/updata',
						method: 'post',
						data: state.addressList[0],
						success: (res) => {
							console.log("修改成功:", res)
						},
						fail() {}
					});
				}

			},
		});

	},
	// 获取购物车数据
	get_user_shopping_cart(state, userId) {
		uni.request({
			url: 'http://localhost:3000/users/shopping_cart',
			method: 'get',
			data: {
				id: userId
			},
			success: (res) => {
				// 直接为每个对象添加新属性
				res.data.forEach(item => {
					item.selected = false
				});
				state.user_shopping_cart = res.data
				console.log("购物车数据res:", res)
			},
		});

	},
	// 获取当前用户参与活动的列表
	get_activity_attend(state, user_id) {
		uni.request({
			url: 'http://localhost:3000/users/activity_attend',
			method: 'GET',
			data: {
				id: user_id
			},
			success: (res) => {
				state.activity_attend = res.data
				console.log("res:", res)
			},
			fail: (res) => {
				console.log(res)
			}
		})
	},
	// 获取数据
	getMessage() {
		uni.request({
			url: 'http://localhost:3000/users',
			method: 'GET',
			data: {
				userName: state.user.account,
				userPassword: state.user.password
			},
			success: (res) => {
				// console.log(res)
				let data = res.data[0]
				//data判断里面有没有数据，数据库中是否有这条数据
				state.user.userId = data.userId
				state.user.account = data.account
				state.user.password = data.password
				state.user.type = data.type
				state.user.nickname = data.nickname
				state.user.image = data.image
				state.user.birthday = data.birthday
				// state = Object.assign({}, state, data)
				// console.log(state.type)
				console.log(data)
				console.log(state)
			}
		})
	},
	//退出登陆                    
	exitlogin() {
		state.user.account = ''
		state.user.password = ''
		uni.navigateTo({
			url: '/pages/login/login'
		})
		console.log(`成功退出登陆`)
	},
	//修改单项属性编辑资料
	changeSingle(state, obj) {
		// console.log(obj)
		Vue.set(state.user, obj.pro, obj.value);
		console.log(state)
	},

	//更改头像
	changeImage(state, fn) {
		uni.chooseImage({
			count: 1, // 默认9
			sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
			success: (res) => {
				const tempFilePaths = res.tempFilePaths;
				state.user.image = tempFilePaths[0]
				uni.uploadFile({
					url: 'http://localhost:3000/images', // 替换为你的Node.js后端地址
					filePath: tempFilePaths[0],
					name: 'file',
					formData: {
						'id': state.user.userId
					},
					success: (uploadRes) => {
						console.log(JSON.parse(uploadRes.data).filePath)
						let images = 'http://localhost:3000' + JSON.parse(uploadRes.data).filePath
						console.log(images)
						state.user.image = images
						console.log("state.image:", state.user.image)
						console.log('上传成功:', JSON.parse(uploadRes.data));
						console.log("state:", JSON.stringify(state.user))
						fn()
					},
					fail: (err) => {
						console.error('上传失败:', err);
					}
				});
				0.
			}
		});
	},
	// 更新数据
	updata(state) {
		console.log("state.user:", JSON.stringify(state.user))
		uni.request({
			url: 'http://localhost:3000/updata',
			method: 'post',
			data: state.user,
			success: (res) => {
				console.log("更新成功")
				console.log("res:", res)
			}
		});
	},
	//登陆
	getuser(state, obj) {
		console.log(obj.account, obj.password)
		uni.request({
			url: 'http://localhost:3000/users/login',
			method: 'GET',
			data: {
				userName: obj.account,
				userPassword: obj.password
			},
			success: (res) => {
				console.log(res)
				let data = res.data[0]
				//data判断里面有没有数据，数据库中是否有这条数据
				if (data) {
					state.user.userId = data.userId
					state.user.account = data.account
					state.user.password = data.password
					state.user.type = data.type
					state.user.nickname = data.nickname
					state.user.image = data.image
					state.user.birthday = data.birthday ? data.birthday.split('T')[0] : data.birthday
					console.log(JSON.stringify(res.data))
					// console.log(state.user)
					uni.showToast({
						title: '登陆成功',
						duration: 1000
					}, );
					setTimeout(function() {
						if (state.user.type == '用户') {
							uni.switchTab({
								url: '/pages/index/index'
							}) //跳转到用户首页
						} else if (state.user.type == '商家') {
							uni.reLaunch({
								url: '/pages/merchant/index'
							})
						} else {
							console.log("前往管理员首页")
							uni.reLaunch({
								url: '/pages/admin/admin'
							})
						}
					}, 1000)
				} else {
					uni.showToast({
						icon: 'error',
						title: '账号或者密码错误',
						duration: 1000
					});
					console.log('账号或者密码错误')
				}
			},
			fail(res) {
				console.log("登陆失败")
			}
		});
	},
	//注册
	postuser(state, obj) {
		uni.request({
			url: 'http://localhost:3000/users',
			method: 'post',
			data: {
				account: obj.account,
				password: obj.password,
				nickname: '默认用户名',
				type: obj.type,
			},
			success: (res) => {
				uni.switchTab({
					url: '/pages/login/login'
				})
				console.log(res.data);
			},
			fail: (res) => {
				console.log(res)
			}
		});
	}
}

const actions = {

}

export default {
	namespaced: true,
	state,
	getters,
	mutations,
	actions,
}